/**
 * Created by xiey on 2016/3/3.
 */
as.directive('anyOtherClick', ['$document', '$parse', function ($document, $parse) {
    return {
        redirect: 'A',
        link    : function (scope, el, attr) {
            var anyOtherClickFunction = $parse(attr['anyOtherClick']);
            var documentClickHandler = function (e) {
                var eventOutsideTarget = !isInclude(el[0], e.target);
                if (eventOutsideTarget) {
                    scope.$apply(function () {
                        anyOtherClickFunction(scope, {});
                    });
                }
            };
            // FIXME 使用 querySelectAll 进行优化
            var isInclude = function (node, includeEl) {
                var result = node === includeEl;
                if (result) {
                    return true;
                }
                if (node.hasChildNodes()) {
                    result = Array.prototype.some.call(node.childNodes, function (current) {
                        return isInclude(current, includeEl);
                    });
                }
                return result;
            };
            $document.on("click", documentClickHandler);
            scope.$on("$destroy", function () {
                $document.off("click", documentClickHandler);
            });
        }
    };
}]);